package com.crl.module.rpc.remoting
{
	import com.crl.utils.HashMap;
	import com.crl.utils.StringUtil;
	
	import flash.utils.Dictionary;
	
	import org.bytearray.remoting.Service;

	public class ServiceFactory
	{
		private static var instances:HashMap;
		public function ServiceFactory()
		{
		}
		
		public static function getInstance(gateway:String):Service{
			var instance:Service=instances.getValue(gateway) as Service;
			if(instance==null){
				
				///是否进行netconnection 共享使用;
				instance=new Service();
				instance.gatewayURL=gateway;
				instances.put(gateway,instance);
			}
			return instance;
		}
		
		/**
		 * 由请求的标识,创建一个远程服务; 
		 * @param key
		 * @return 
		 * 
		 */		
		public function getServiceByKey(key:String="*"):Service{
			var vo:RemotingVO=services[key] as RemotingVO;
			if(vo==null){
				throw new Error(StringUtil.substitute("不存在{0} 的定义",key));
			}
			var sc :Service = ServiceFactory.getInstance(vo.gateway);
			sc.service=vo.service;
			return sc;
		}
		
		
		private var services:Dictionary;
		public function set serviceConfig(value:XML):void{
			services=new Dictionary(true);
			
			var remoting:XML=value.copy();
			var servers:XMLList=remoting.descendants("server");
			
			var parmValue:String;
			var key:String;
			for each(var item:XML in servers){
				key=item.@key;
				services[key]=new RemotingVO().bindXML(item);
				if(services["*"]==null)services["*"]=services[key];
			}
			
		}
		
	}
}